package com.moresir.validatetools.parser;

import com.moresir.validatetools.common.response.ResponseEnum;
import com.moresir.validatetools.exceptions.BusinessException;
import com.moresir.validatetools.RuleInfo;
import com.moresir.validatetools.exceptions.LexerExceptionEnum;
import com.moresir.validatetools.impl.RuleDescriptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.moresir.validatetools.config.ValidatorConfig.cfg;

public class RuleParser {
    public static List<RuleInfo> getRuleInfo(String field, String inputRule) {
        List<RuleInfo> lst = new ArrayList<>();
        List<RuleLexer.Token> lex = new RuleLexer(inputRule).lex();
        for (RuleLexer.Token tok : lex) {
            Optional<RuleDescriptor> rule = cfg().ruleList.getRule(tok.getParams().size(), tok.getRuleName().toString());
            if (!rule.isPresent())
                throw new BusinessException(ResponseEnum.VALIDATE_RULE_LEXER_ERROR.getCode(), String.format(LexerExceptionEnum.NO_RULES_CONFIG.getZhMsg(), inputRule, field));
            lst.add(new RuleInfo(field, rule.get(), tok));
        }
        return lst;
    }
}
